import request from '@/request'

/**
 * @description: 上传分片
 * @param {*} chunk 分片
 * @param {*} chunkFileName 分片名称
 * @param {*} fileName 文件名称
 * @param {*} setUploadProgress 设置上传进度
 * @param {*} abortController 取消请求
 * @param {*} start 字节的偏移量
 * @param {*} totalSize 分片总大小
 * @return {*}
 */
export const uploadChunk = (chunk, chunkFileName, fileName, setUploadProgress, abortController, start, totalSize) => {
  return request.post(`/upload/${fileName}`, chunk, {
    headers: {
      // 字节流
      'Content-Type': 'application/octet-stream',
    },
    params: {
      // 分片名称
      chunkFileName,
      // 字节的偏移量
      start
    },
    onUploadProgress: (progressEvent) => {
      const computedProgress = Math.round(((progressEvent.loaded + start) / totalSize) * 100)
      setUploadProgress((prev) => ({ ...prev, [chunkFileName]: computedProgress }))
    },
    signal: abortController.signal
  })
}

/**
 * @description: 合并分片
 * @param {*} fileName
 * @return {*}
 */
export const mergeChunks = (fileName) => {
  return request.get(`/merge/${fileName}`)
}

/**
 * @description: 验证文件是否存在
 * @param {*} fileName
 * @return {*}
 */
export const verifyFile = (fileName) => {
  return request.get(`/verify/${fileName}`)
}
